package com.zyz.zchat;

import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Label;

import com.jfoenix.controls.JFXButton;
import com.jfoenix.controls.JFXListView;
import com.jfoenix.controls.JFXTextArea;
import javafx.fxml.FXML;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.ArrayList;

public class ZChatController {
    private BroadcastManager manager=new BroadcastManager();

    private ChatManager chatManager=new ChatManager();

    Chat currChat;
    @FXML
    private JFXTextArea inputField;

    @FXML
    private JFXListView<Message> Messages;

    @FXML
    private JFXButton submitButton;

    @FXML
    private JFXButton refreshButton;

    @FXML
    private JFXListView<InetAddress> clientList;
    @FXML
    private Label currHost;

    @FXML
    void submit(ActionEvent event) {
        if(currChat!=null&&!inputField.getText().isEmpty())
            currChat.sendMessage(inputField.getText());
        inputField.clear();

    }
    private ObservableList<InetAddress> hosts=FXCollections.observableList(new ArrayList<>());
    @FXML
    void refresh(ActionEvent event) {
        try {
            manager.broadcast();
        } catch (IOException e) {
            e.printStackTrace();
        }
        clientList.setItems(hosts);
        hosts.clear();
        hosts.addAll(manager.hosts);
    }
    void initListener()
    {
        clientList.getSelectionModel().selectedItemProperty().addListener(
                (observable, oldValue, newValue) ->
                {
                    InetAddress selected=clientList.getSelectionModel().getSelectedItem();
                    if(!chatManager.chats.containsKey(selected))
                    {
                        try {
                            chatManager.addChat(new Chat(selected));

                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    currChat=chatManager.chats.get(selected);
                    Messages.setItems(currChat.allMessages);
                    currHost.setText("当前连接："+selected);

                });
    }
}
